$(function() {
    var operateLog = {
        /* 初始数据 */
        defData: {
            pageSize: 20
        },

        /* 页面状态 */
        pageState: {
            page: 1, // 分页值
            search: {
                type: 'ip',
                content: '',
                startTime: '',
                endTime: ''
            },
            sort: {
                log_id: 'desc' // 创建时间(def：默认; asc:正序; desc：倒序)
            },
            noData: 'def' // search: 没有匹配的结果; def: 暂无记录.
        },

        /* 搜索 */
        searchEvent: function() {
            var _this = this,
                searchInput = $('.bdb-search-input'),
                searchType = $('#bdb-opeartion-log-search-type');

            $('.search-btn').off('click').on('click', function(e) {
                e.stopPropagation();
                searchType.show();
            });

            searchType.off('click').on('click', 'li', function(e) {
                e.stopPropagation();
                var ele = $(e.target),
                    dataType = ele.attr('data-type');

                $('.search-left-select').find('em').text(ele.text()).attr('data-type', dataType);
                _this.pageState.search.type = dataType;
                searchType.hide();
            });

            searchType.parents('.search-left-select').off('mouseleave').on('mouseleave', function() {
                searchType.hide();
            });

            searchInput.off('focusin').on('focusin', '.search-text', function(e) {
                e.stopPropagation();
                var _cThis = $(this),
                    _btnEle = $(this).parent().find('.search-conf');

                if (!_btnEle.hasClass('search-clear')) {
                    _cThis.animate({width: '240px'}, 500);
                    _btnEle.animate({left: '240px'}, 500, function() {
                        _btnEle.removeClass('search-gray').addClass('search-blue');
                    });
                }
            });

            searchInput.off('click').on('click', 'span', function(e) {
                e.stopPropagation();
                var left = parseInt($(this).css('left'));
                if ($(this).hasClass('search-blue') && left > 0) {
                    _this.pageState.search.content = searchInput.find('.search-text').val();
                    _this.pageState.noData = 'search';
                    $(this).removeClass('search-blue').addClass('search-clear');
                    _this.list();
                } else if (left > 0){
                    _this.pageState.search.content = '';
                    _this.pageState.noData = 'def';
                    searchInput.find('.search-text').val('');
                    $(this).removeClass('search-clear').addClass('search-blue');
                    _this.list();
                }
            });
        },

        /* 列表 */
        listEvent: function() {
            var _this = this;
            $('.bdb-list').off('click.listEvent').on('click.listEvent', function(e) {
                e.stopPropagation();
                var ele = $(e.target),
                    logId = ele.parents('.bdb-list-row').attr('data-logId');

                if (ele.hasClass('js-bdb-log-detail')) {
                    _this.logDetail(logId);
                }
            });
        },
        listProc: function(data) {
            var tpl = '';

            $.each(data.logList, function(i, n) {
                tpl += '<div class="bdb-list-row" data-logId="' + n.log_id + '">\
                           <div class="bdb-mx-w-col-1">' + n.log_id + '</div>\
                           <div class="bdb-mx-w-col-2 bdb-ellipsis">' + n.action + '</div>\
                           <div class="bdb-mx-w-col-3 bdb-ellipsis js-bdb-log-detail">' + n.brief + '</div>\
                           <div class="bdb-mx-w-col-4">' + n.create_time + '</div>\
                           <div class="bdb-mx-w-col-5">' + n.ip + '</div>\
                           <div class="bdb-mx-w-col-6 bdb-ellipsis">' + n.username + '</div>\
                           <div class="bdb-mx-w-col-7"><div class="bdb-option-btn js-bdb-log-detail">详细信息</div></div>\
                       </div>';
            });

            return tpl;
        },
        list: function(obj) {
            var _this = this,
                obj = obj || {page: 1},
                params = {};

            _this.pageState.page = obj.page;
            params = {
                pageSize: _this.defData.pageSize,
                pageNumber: _this.pageState.page,
                orderBy: _this.pageState.sort,
                startTime: _this.pageState.search.startTime,
                endTime: _this.pageState.search.endTime
            };
            params[_this.pageState.search.type] = _this.pageState.search.content;
            bdbMain.mLRManag({mask: true, loading: true});

            // 获取列表.
            $.post('/AdminOperateLog/logList', params, function(response) {
                var totalRowCnt = 0,
                    listHtml = '';

                if (response.code == 0) {
                    totalRowCnt = parseInt(response.data.totalCount) > 0 ? parseInt(response.data.totalCount) : 0;
                    listHtml = _this.listProc(response.data);
                    _this.listNull(totalRowCnt);
                    $('.bdb-list').html(listHtml);
                    bdbMain.mLSleep({mask: false, loading: false});

                    // 分页
                    $("#logListPage").bdbPagination({
                        totalRowCnt: totalRowCnt,
                        currentPage: _this.pageState.page,
                        pageSize: _this.defData.pageSize
                    });
                    $('.bdb-record-cnt').html(bdbMain.pageInfo.recordCnt.replace('{cnt}', totalRowCnt));
                } else {
                    bdbMain.mLSleep({mask: false, loading: false, alert: {type: 2, msg: response.msg}});
                }
            });
        },

        /* 日志详情 */
        logDetail: function(logId) {
            var _this = this;
            $.post('/AdminOperateLog/logDetail', {
                logId: logId
            }, function(response) {
                if (response.code == 0) {
                    $('.bdbBlankEle').bdbDialog({
                        ele: '#bdb-opeartion-log-detail-dialog',
                        css: {
                            width: '780px',
                            'margin-left': '-390px'
                        },
                        contentCss: {
                            padding: '20px',
                            'max-height': '480px',
                            'border-radius': '4px',
                            overflow: 'auto'
                        }
                    });

                    $('#bdb-opeartion-log-detail-dialog > .content').scrollTop(0).html('<pre>' + _this.formatJson(response.data) + '</pre>');
                } else {
                    bdbMain.alert({type: 2, msg: response.msg});
                }
            });
        },
        listNull: function(totalRowCnt) {
            var noResult = $('.bdb-no-result'),
                noSearchRecord = $('.bdb-no-search-record');

            if (totalRowCnt <= 0) {
                if (this.pageState.noData == 'search') { // 查询.
                    noResult.hide();
                    noSearchRecord.show();
                } else { // 暂无记录.
                    noResult.show();
                    noSearchRecord.hide();
                }
            } else {
                noResult.hide();
                noSearchRecord.hide();
            }
        },

        /* 分页 */
        pageEvent: function() {
            var _this = this;

            /* 页码事件 */
            $('.bdb-creatPage').off('click').on('click', '.bdb-pagination', function(e) {
                e.preventDefault();
                var ele = $(e.target),
                page = parseInt(ele.text());

                if (!isNaN(page)) {
                    _this.list({page: page});
                }
            });
        },

        /* 屏幕高度适应 */
        contentSizeResize: function() {
            $(window).resize(function() {
                $('.bdb-list').bdbScreenH(1);
            });
        },

        /* json格式化 */
        formatJson: function(json, options) {
            var reg = null,
                formatted = '',
                pad = 0,
                PADDING = '    ';

            // optional settings
            options = options || {};
            // remove newline where '{' or '[' follows ':'
            options.newlineAfterColonIfBeforeBraceOrBracket = (options.newlineAfterColonIfBeforeBraceOrBracket === true) ? true : false;
            // use a space after a colon
            options.spaceAfterColon = (options.spaceAfterColon === false) ? false : true;

            // begin formatting...
            if (typeof json !== 'string') {
                // make sure we start with the JSON as a string
                json = JSON.stringify(json);
            } else {
                // is already a string, so parse and re-stringify in order to remove extra whitespace
                json = JSON.parse(json);
                json = JSON.stringify(json);
            }

            // add newline before and after curly braces
            reg = /([\{\}])/g;
            json = json.replace(reg, '\r\n$1\r\n');

            // add newline before and after square brackets
            reg = /([\[\]])/g;
            json = json.replace(reg, '\r\n$1\r\n');

            // add newline after comma
            reg = /(\,)/g;
            json = json.replace(reg, '$1\r\n');

            // remove multiple newlines
            reg = /(\r\n\r\n)/g;
            json = json.replace(reg, '\r\n');

            // remove newlines before commas
            reg = /\r\n\,/g;
            json = json.replace(reg, ',');

            // optional formatting...
            if (!options.newlineAfterColonIfBeforeBraceOrBracket) {
                reg = /\:\r\n\{/g;
                json = json.replace(reg, ':{');
                reg = /\:\r\n\[/g;
                json = json.replace(reg, ':[');
            }

            if (options.spaceAfterColon) {
                reg = /\:/g;
                json = json.replace(reg, ': ');
            }

            $.each(json.split('\r\n'), function(index, node) {
                var i = 0,
                    indent = 0,
                    padding = '';

                if (node.match(/\{$/) || node.match(/\[$/)) {
                    indent = 1;
                } else if (node.match(/\}/) || node.match(/\]/)) {
                    if (pad !== 0) {
                        pad -= 1;
                    }
                } else {
                    indent = 0;
                }

                for (i = 0; i < pad; i++) {
                    padding += PADDING;
                }

                formatted += padding + node + '\r\n';
                pad += indent;
            });

            return formatted;
        },

        /* date */
        dateEvent: function() {
            var _this = this,
                searchDate = $('#bdb-opeartion-log-search-date'),
                startDate = '2017-02-01 00:00',
                endDate = moment().subtract('days', 0).format("YYYY-MM-DD 23:59");

            searchDate.find('span').html(startDate + ' - ' + endDate);
            searchDate.daterangepicker({
                parentEl: $(".bdb-main .bdb-container"), //设置父元素.
                startDate: startDate,
                endDate: endDate,
                minDate: startDate,
                maxDate: endDate,
                format: 'YYYY-MM-DD HH:mm',
                opens: 'right',
                timePicker: true, // 是否开启时间选择.
                timePicker12Hour: false, // 是否开始时间选择-12小时制.
                timePickerIncrement: 1 // 是否开始时间选择-分钟步长.
            }, function(start, end, label) {
                var startTime = start.format('YYYY-MM-DD HH:mm'),
                    endTime = end.format('YYYY-MM-DD HH:mm');

                if (endTime < startTime) {
                    bdbMain.mLRManag({alert: {type: 2, msg: '结束时间不能小于开始时间!'}});
                    return ;
                }

                searchDate.find('span').html(startTime + ' - ' + endTime);
                _this.pageState.search.startTime = start.format('X');
                _this.pageState.search.endTime = end.format('X');
                _this.list();
            });
        },
        dateEventProc: function() {
        },

        /* 初始化 */
        init: function() {
            var _this = this;

            _this.list(); // 加载列表
            _this.listEvent(); // 列表操作事件
            _this.pageEvent(); // 分页事件
            _this.searchEvent(); // 搜索
            _this.contentSizeResize(); //内容区域屏幕适应
            _this.dateEvent();

            $('.bdb-list').bdbScreenH(1); // 右侧列表区域自适应
        }
    };

    operateLog.init();
});
